package com.sczfdf.www.sda.gov.cn.tool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.sczfdf.www.sda.gov.cn.dao.C3P0ConnentionProvider;

public class UserAgentTool {
	private static String SQL = "select * from useragent";
	static List<String> userAgents = new ArrayList<>();
	static Integer userAgentCount;
	static Random rand = new Random();
	
	static{
		PreparedStatement ps = null;
		Connection conn = null;
		ResultSet rs = null;
		try {
			conn = C3P0ConnentionProvider.getConnection();
			ps = conn.prepareStatement(SQL);
			rs = ps.executeQuery();
			
	        while (rs.next()) {//只有一列
	            userAgents.add( (String)rs.getObject(1) );
	        }
	        
	        userAgentCount = userAgents.size();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(ps != null){
					ps.close();
				}
				if(rs != null){
					rs.close();
				}
				if(conn!=null){
		            try {  
		                conn.close();  
		            } catch (SQLException e) {  
		            	e.printStackTrace();  
		            }  
		        } 
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				
			}
		}
	}
	
	public static String getUserAgent() {
		return userAgents.get(rand.nextInt(userAgentCount));
	}
	
}
